const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
//算法有非常多种类，最常用  md5、sha1
var types = crypto.getHashes();
let str = 'hello world';

console.log(types);

//----散列算法----
var md5 = crypto.createHash('md5');
// hello world 为摘要原始内容
md5.update(str);  //这里可以传 buffer 吗?
var r = md5.digest('hex');
//digest 之前可以多次 update
console.log(`result: ${r}`);

//----散列 + 密钥 算法----
var shahash = crypto.createHash('sha1');
var rs = fs.createReadStream(path.resolve(__dirname, 'data.txt'));
rs.on('data', (chunk)=>{
    // console.log('chunk 类型：');
    // console.log(chunk);
    shahash.update(chunk);
})

rs.on('end', ()=>{
    let result = shahash.digest('hex');
    console.log(`sha1 result: ${result}`);
});

//----对称加密算法----
// console.log(`__dirname:  ${__dirname}`);
// let cipher = crypto.createCipher('blowfish',fs.readFileSync(path.resolve(__dirname, 'keys/c')));
// let encry = cipher.update(str, 'utf8', 'hex');
// encry +=cipher.final('hex');
// console.log(`encry: ${encry}`);

// let decipher = crypto.createCipher('blowfish',fs.readFileSync(path.resolve(__dirname, 'keys/id_rsa')));
// let deencry = decipher.update(str, 'hex', 'utf8');
// deencry +=decipher.final('utf8');
// console.log(`encry: ${deencry}`);

//----非对称加密算法----
let key = fs.readFileSync(path.resolve(__dirname, 'keys/id_rsa'));
let cert = fs.readFileSync(path.resolve(__dirname, 'keys/id_rsa.pub'));
//公钥加密报错，这里的 str 一定要是 buffer 吗？不可以是字符串吗？
let secret = crypto.publicEncrypt(cert, Buffer.from(str));  //公钥加密
// let result = crypto.privateDecrypt(key, secret);  //私钥解密
// console.log('result:');
// console.log(result);